<script setup>
import { ref, computed, onMounted } from "vue";
import { LocalDateTime } from '@/utils/format'
import * as echarts from 'echarts';
import { orderTurnover, orderUser, orderOrder, orderGoods } from '@/api/order'
// 字符串转数组
const strToArray = (str) => {
  return str.substring(1, str.length - 1).split(',');
}

const dateSelection = ref('昨天');
const today = LocalDateTime(new Date());
const options = ['昨天', '近7日', '近30日', '本周', '本月'];
const totalOrderNum = ref(0);
const validOrderNum = ref(0);
const validOrderRatio = ref(0);
// 初始销量图
const initSalesChart = (nameList, numberList) => {
  let salesChart = echarts.init(document.getElementById('sales-chart'));
  salesChart.setOption({
    title: {
      text: '销量统计'
    },
    // 新增 axisLabel 配置

    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: nameList,
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          formatter: function (params) {
            console.log(params);

            var newParamsName = ''; // 拼接后的新字符串
            var paramsNameNumber = params.length; // 实际标签数
            var provideNumber = 3; // 每行显示的字数
            var rowNumber = Math.ceil(paramsNameNumber / provideNumber); // 如需换回，算出要显示的行数

            if (paramsNameNumber > provideNumber) {
              /** 循环每一行,p表示行 */

              for (var i = 0; i < rowNumber; i++) {
                var tempStr = ''; // 每次截取的字符串
                var start = i * provideNumber; // 截取位置开始
                var end = start + provideNumber; // 截取位置结束

                // 最后一行的需要单独处理

                if (i == rowNumber - 1) {
                  tempStr = params.substring(start, paramsNameNumber);
                } else {
                  tempStr = params.substring(start, end) + '\n';
                }
                newParamsName += tempStr;
              }
            } else {
              newParamsName = params;
            }

            return newParamsName;
          }
        },
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: 'Direct',
        type: 'bar',
        barWidth: '60%',
        data: numberList
      }
    ]
  })
}
// 初始订单图
const initOrderChart = (dateList, totalOrderList, validOrderList) => {
  let orderChart = echarts.init(document.getElementById('order-chart'));
  orderChart.setOption({
    title: {
      text: '订单统计'
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['已完成订单数', '总订单数']
    },
    xAxis: {
      type: 'category',
      data: dateList
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: validOrderList,
        type: 'line',
        name: '已完成订单数'
      },
      {
        data: totalOrderList,
        type: 'line',
        name: '总订单数'
      }
    ]

  });
}
// 初始用户数图
const initUserChart = (dateList, totalUserList, newUserList) => {
  let userChart = echarts.init(document.getElementById('user-chart'));
  userChart.setOption({
    title: {
      text: '用户统计'
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['新添用户数', '总用户数']
    },
    xAxis: {
      type: 'category',
      data: dateList
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: newUserList,
        type: 'line',
        name: '新添用户数'
      },
      {
        data: totalUserList,
        type: 'line',
        name: '总用户数'
      }
    ]
  });
}

// 初始营业额图

const initTurnoverChart = (dateList, turnoverList) => {
  let turnoverChart = echarts.init(document.getElementById('turnover-chart'));
  turnoverChart.setOption({
    title: {
      text: '营业额'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      },
      formatter: function (params) {
        let result = `${params[0].axisValue}<br/>`;
        result += `${params[0].marker} 营业额: ${params[0].value}<br/>`;
        return result;
      }
    },
    xAxis: {
      type: 'category',
      data: dateList
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: turnoverList,
        type: 'line'
      }
    ]
  });
}
onMounted(async () => {
  const { result } = await orderTurnover(startDate.value, today)
  const dateList = strToArray(result.dateList);
  const turnoverList = strToArray(result.turnoverList);
  const result1 = await orderUser(startDate.value, today)
  const totalUserList = strToArray(result1.result.totalUserList);
  const newUserList = strToArray(result1.result.newUserList);
  const result2 = await orderOrder(startDate.value, today)
  const totalOrderList = strToArray(result2.result.totalOrderList);
  const validOrderList = strToArray(result2.result.validOrderList);
  const result3 = await orderGoods(startDate.value, today)
  const nameList = strToArray(result3.result.nameList);
  const numberList = strToArray(result3.result.numberList);

  // 遍历总订单和有效订单，计算总和
  totalOrderNum.value = totalOrderList.reduce((pre, cur) => pre + parseInt(cur), 0);
  validOrderNum.value = validOrderList.reduce((pre, cur) => pre + parseInt(cur), 0);
  // 计算总订单和有效订单的比例
  validOrderRatio.value = validOrderNum.value / totalOrderNum.value * 100 ? validOrderNum.value / totalOrderNum.value * 100 : 0;


  initTurnoverChart(dateList, turnoverList);
  initUserChart(dateList, totalUserList, newUserList);
  initOrderChart(dateList, totalOrderList, validOrderList)
  initSalesChart(nameList, numberList)
})

// 封装营业额数据和时间轴
const getTurnoverData = async () => {
  const { result } = await orderTurnover(startDate.value, today)
  const dateList = strToArray(result.dateList);
  const turnoverList = strToArray(result.turnoverList);
  initTurnoverChart(dateList, turnoverList);
}
// 封装用户数据和时间轴
const getUserData = async () => {
  const result1 = await orderUser(startDate.value, today)
  const dateList = strToArray(result1.result.dateList);
  const totalUserList = strToArray(result1.result.totalUserList);
  const newUserList = strToArray(result1.result.newUserList);
  initUserChart(dateList, totalUserList, newUserList);
}
// 封装订单数据和时间轴
const getOrderData = async () => {
  const result2 = await orderOrder(startDate.value, today)
  const dateList = strToArray(result2.result.dateList);
  const totalOrderList = strToArray(result2.result.totalOrderList);
  const validOrderList = strToArray(result2.result.validOrderList);
  totalOrderNum.value = totalOrderList.reduce((pre, cur) => pre + parseInt(cur), 0);
  validOrderNum.value = validOrderList.reduce((pre, cur) => pre + parseInt(cur), 0);
  validOrderRatio.value = validOrderNum.value / totalOrderNum.value * 100 ? validOrderNum.value / totalOrderNum.value * 100 : 0;

  initOrderChart(dateList, totalOrderList, validOrderList);
}
// 封装销量数据和商品名称
const getSalesData = async () => {
  const result3 = await orderGoods(startDate.value, today)
  const nameList = strToArray(result3.result.nameList);
  const numberList = strToArray(result3.result.numberList);

  initSalesChart(nameList, numberList);
}
// 计算开始时间
const startDate = computed(() => {
  const now = new Date();
  const start = new Date();

  switch (dateSelection.value) {
    case '昨天':
      start.setDate(now.getDate() - 1);
      break;
    case '近7日':
      start.setDate(now.getDate() - 6); // 近7日包含今天，所以减6

      break;
    case '近30日':
      start.setDate(now.getDate() - 29); // 近30日包含今天，所以减29

      break;
    case '本周':
      start.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1)); // 本周周一

      break;
    case '本月':
      start.setDate(1); // 本月1号

      break;
    default:
      return LocalDateTime(start);
  }

  return LocalDateTime(start);
});

const handleDateChange = () => {
  getTurnoverData()
  getUserData()
  getOrderData()
  getSalesData()
}
</script>

<template>
  <div>
    <div>
      <el-segmented v-model="dateSelection" :options="options" size="large" @change="handleDateChange" />
      <span style="font-size: 14px; color: skyblue;">已选时间:{{ startDate }}至{{ today }}</span>
    </div>
    <div>
      <div class="top-charts">
        <div id="turnover-chart" style="width: 600px;height:400px;"></div>
        <div id="user-chart" style="width: 600px;height:400px;"></div>
      </div>
      <div class="bottom-charts">
        <div>
          <div class="order-stat">
            订单完成率：{{ validOrderRatio.toFixed(1) }}% = {{ validOrderNum }} / {{ totalOrderNum }}
          </div>
          <div id="order-chart" style="width: 600px;height:400px;"></div>
        </div>
        <div id="sales-chart" style="width: 600px;height:400px;"></div>
      </div>

    </div>
  </div>
</template>

<style scoped>
html {
  background-color: #f0eff4;
}

.top-charts {
  display: flex;
}

.order-stat {
  width: 600px;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
  text-align: center;
}

.bottom-charts {
  display: flex;
}
</style>
